package soar.template.springboot.service.hello.configuration.aspect;

import java.io.BufferedReader;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.databind.ObjectMapper;

@Aspect
@Order(5)
@Component
public class MyWeblogAspect
{
    private final static Logger logger = LoggerFactory
            .getLogger(MyWeblogAspect.class);

    @Pointcut("execution(public * soar.template.springboot.service.hello.controller.hello.HelloController.*(..))"
            + " and @annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void weblog()
    {
    }

    @Before("weblog()")
    public void doBefore(JoinPoint join_point) throws Throwable
    {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest servlet_request = attributes.getRequest();
        try
        {
            BufferedReader br = servlet_request.getReader();
            StringBuilder sbld = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null)
            {
                sbld.append(line);
            }
            String request = sbld.toString().trim();
            logger.info("request: {}", request);
        }
        catch (Exception e)
        {
            logger.error("wrapped request error: {}", e);
        }

    }

    @AfterReturning(returning = "ret", pointcut = "weblog()")
    public void doAfterReturning(Object ret) throws Throwable
    {
        logger.info("response: {}", new ObjectMapper().writeValueAsString(ret));
    }
}
